<template>
  <div class="app-container org">
    <el-card class="leftCard">
      <!-- 搜索条件盒子 -->
      <div>
        <p class="pinformation">搜索条件</p>
        <el-form :model="queryParams">
          <el-row>
            <el-col :span="16">
              <el-form-item label="机构名称：" prop="orgName">
                <el-input clearable placeholder="请输入机构名称" v-model="queryParams.orgName" maxlength="100"
                  @keyup.enter="handleQuery" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="关键字：" prop="keyWord" label-width="70">
                <el-input clearable placeholder="关键字" v-model="queryParams.keyWord" maxlength="100"
                  @keyup.enter="handleQuery" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="18">
              <el-form-item label="机构地区：">
                <City @queryParam="cityQueryParam" :id="'left'" ref="areaRef" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-row justify="end">
                <el-button type="success" @click="handleQuery">搜索</el-button>
                <el-button class="resetBtn" @click="resetQuery">重置</el-button>
              </el-row>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <!-- 机构列表盒子 -->
      <div>
        <el-row style="justify-content: space-between;">
          <el-row>
            <p class="pinformation">机构列表</p>
            <p class="totalStyle">共 {{ total }} 条数据</p>
          </el-row>
          <el-row style="margin-bottom: 5px;">
            <el-button type="success" link @click="handleAddOrg">
              <el-icon>
                <Plus />
              </el-icon>新增
            </el-button>
            <el-button type="success" link icon="Delete" @click="handleDelete"
              :disabled="multiple > 0 ? false : true">删除</el-button>
          </el-row>
        </el-row>
        <el-table class="business" v-loading="loading" :row-class-name="tableRowClass" :data="orgTable" ref="mainTableRef"
          @row-click="rowClick" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="机构名称" width="270" align="center" prop="orgName" />
          <el-table-column label="操作" align="center">
            <template #default="scope">
              <el-button link type="success" icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize" @pagination="getList" />
      </div>
    </el-card>
    <el-card class="rightCard">
      <!-- 基础信息 -->
      <el-form label-width="130px" :model="form" :rules="rules" ref="orgRef">
        <div>
          <el-row style="margin-bottom: 5px">
            <el-col :span="22">
              <p class="pinformation">基础信息</p>
            </el-col>
            <el-col :span="2">
              <el-button type="success" size="small" @click="submitForm">保存</el-button>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="16">
              <el-form-item label="机构名称：" prop="orgName">
                <el-input placeholder="请输入机构名称" v-model="form.orgName" clearable maxlength="100" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="搜索关键字：" prop="keyWord">
                <el-input clearable placeholder="请输入关键字" v-model="form.keyWord" maxlength="100" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="公司地址：" prop="areaCode">
                <City @queryParam="cityQueryParam" :id="'right'" @areaCode="areaCode" :viewForm="viewCity" />
              </el-form-item>
            </el-col>
            <el-col :span="16">
              <el-form-item label="详细地址：" prop="orgAddress">
                <el-input clearable placeholder="请输入详细地址" v-model="form.orgAddress" maxlength="100" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="法人姓名：" prop="personName">
                <el-input placeholder="请输入法人姓名" v-model="form.personName" clearable maxlength="100" />
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item label="法人联系方式：" prop="personPhonenumber">
                <el-input clearable placeholder="法人联系方式" v-model="form.personPhonenumber" />
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item label="业务联系人：" prop="busName">
                <el-input placeholder="业务联系人" v-model="form.busName" clearable maxlength="100" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="业务联系人电话：" prop="busPhonenumber">
                <el-input clearable placeholder="请输入业务联系人电话" v-model="form.busPhonenumber" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="公司邮箱：" prop="orgEmail">
                <el-input clearable placeholder="请输入公司邮箱" v-model="form.orgEmail" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="公司传真：" prop="orgFax">
                <el-input placeholder="请输入公司传真" v-model="form.orgFax" clearable maxlength="100" />
              </el-form-item>
            </el-col>
          </el-row>
        </div>
        <!-- 财务信息 -->
        <div>
          <p class="pinformation">财务信息</p>
          <el-row>
            <el-col :span="14">
              <el-form-item label="纳税人识别号：" prop="taxpayerNumber">
                <el-input clearable placeholder="请输入纳税人识别号" v-model="form.taxpayerNumber" maxlength="100" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="银行账号：" prop="bankNumber">
                <el-input maxlength="100" clearable placeholder="请输入银行账号" v-model="form.bankNumber" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="7">
              <el-form-item label="开户行：" prop="bankName">
                <el-input placeholder="请输入开户行" v-model="form.bankName" clearable maxlength="100" />
              </el-form-item>
            </el-col>
            <el-col :span="7">
              <el-form-item label="发票类型：">
                <el-select v-model="form.invoiceType" placeholder="请选择发票类型" clearable>
                  <el-option v-for="dict in sys_invoice_type" :key="parseInt(dict.value)" :label="dict.label"
                    :value="parseInt(dict.value)"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="发票点数（%）：" prop="invoiceCount">
                <el-input show-word-limit maxlength="2" placeholder="请输入发票点数（%）" v-model="form.invoiceCount" clearable />
              </el-form-item>
            </el-col>
          </el-row>
        </div>
        <!-- 系统管理员信息 -->
        <div>
          <p class="pinformation">系统管理员信息</p>
          <el-row>
            <el-col :span="10">
              <el-form-item label="管理员账号：" prop="userName">
                <el-input show-word-limit :disabled="form.orgId ? true : false" clearable maxlength="15"
                  placeholder="请输入管理员账号" v-model="form.userName" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-button link type="success" style="margin-top: 5px">密码重置</el-button>
            </el-col>
          </el-row>
        </div>
        <!-- 业务信息 -->
        <div>
          <p class="pinformation">业务信息</p>
          <el-row>
            <el-col :span="24">
              <el-form-item label="检测类别：" prop="jclbIds">
                <el-select v-model="form.jclbIds" placeholder="请选择检测类别" style="width:100%" filterable multiple clearable>
                  <el-option v-for="item in jclbList"  :key="item.jclbId"
                    :value="item.jclbId"
                    :label="item.jclbName">{{ item.jclbName }}({{ item.jclbGroupName }})</el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </el-form>
      <!-- 资质证书 -->
      <div>
        <div>
          <el-row>
            <p class="pinformation">资质证书</p>
            <p class="totalStyle">共 {{ form.sysOrgCertificateList.length }} 条数据</p>

            <el-row style="margin-bottom: 5px; margin-left: 20px;">
              <el-button type="success" link icon="Plus" @click="handleAdd">新增</el-button>
            </el-row>
          </el-row>
        </div>
        <el-table :data="form.sysOrgCertificateList" v-loading="zsLoading" class="business" ref="subTableRef">
          <el-table-column label="证书名称" align="center" prop="certificateName" />
          <el-table-column label="证书编号" align="center" prop="certificateNumber" width="200" />
          <el-table-column label="开始时间" align="center" prop="startDate" width="100" />
          <el-table-column label="结束时间" align="center" prop="endDate" width="100">
            <template #default="scope">
              {{ scope.row.endDate ? scope.row.endDate : '永久' }}
            </template>
          </el-table-column>
          <el-table-column label="当前状态" align="center" prop="status" width="100">
            <template #default="scope">
              {{ scope.row.status ? '作废' : '正常' }}
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" type="index" width="210">
            <template #default="scope">
              <el-button link icon="View" @click="handleListView(scope.row)">查看</el-button>
              <el-button link icon="EditPen" @click="handleListEditor(scope.row, scope.$index)">编辑</el-button>
              <el-button link icon="Delete" @click="handleListDelete(scope.$index)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>

    <!-- 新增修改弹出框 -->
    <el-dialog :class="'el-dialog-theme3'" v-model="open" :title="title" append-to-body draggable
      :close-on-click-modal="false">
      <el-form label-width="85px" :model="certificateForm" :disabled="disabled" :rules="certificateRules" ref="listRef">
        <el-form-item label="证书名称：" prop="certificateName">
          <el-input clearable placeholder="请输入证书名称" v-model="certificateForm.certificateName" maxlength="100" />
        </el-form-item>
        <el-form-item label="证书编号：">
          <el-input clearable placeholder="请输入证书编号" v-model="certificateForm.certificateNumber" maxlength="100" />
        </el-form-item>
        <el-row>
          <el-col :span="8">
            <el-form-item label="开始时间：">
              <el-date-picker v-model="certificateForm.startDate" placeholder="请输入开始时间" type="date"
                value-format="YYYY-MM-DD" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="结束时间：">
              <el-date-picker placeholder="请输入结束时间" v-model="certificateForm.endDate" value-format="YYYY-MM-DD"
                type="date" @change="endDateChange" />
            </el-form-item>
          </el-col>

          <el-col :span="2" :offset="1">
            <el-checkbox label="永久" v-model="checkbox" @change="checkboxCheck" />
          </el-col>
          <el-col :span="5">
            <el-form-item label="状态：" label-width="50px">
              <el-select placeholder="选择状态" clearable v-model="certificateForm.status">
                <el-option v-for="item in condition" :key="item.status" :label="item.name" :value="item.status" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- <el-upload
          v-model:file-list="fileList"
          class="upload-demo"
          action="https://run.mocky.io/v3/9d059bf9-4660-45f2-925d-ce80ad6c4d15"
          multiple
          :limit="3"
          :auto-upload="false"
        >
          <el-button type="success" link>选择文件</el-button>
          <template #tip>
            <div class="el-upload__tip">
              jpg/png files with a size less than 500KB.
            </div>
          </template>
        </el-upload>-->
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="success" @click="sava">保存</el-button>
          <el-button @click="Cancel" type="danger">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Org">
import { listOrg, addOrg, delOrg, getOrg } from "@/api/system/org";
import { getSeqId } from "@/api/common";
import useOrg from "@/store/modules/org";
import City from "@/components/City/index.vue";
const { proxy } = getCurrentInstance();
const { jclbList } = proxy.useJclb();
const orgStore = useOrg();
const { sys_invoice_type } = proxy.useDict("sys_invoice_type");
const open = ref(false);
const title = ref("");
const fileList = ref([]);
const orgTable = ref([]);
const total = ref(0);
const certificateForm = ref({});
const disabled = ref(false);
const multiple = ref();
const ids = ref([]);
const areaRef = ref(null);
const highLightRow = ref(true);
const loading = ref(true);
const zsLoading = ref(false);
const checkbox = ref(true);

const condition = ref([
  { name: "正常", status: "0" },
  { name: "作废", status: "1" }
]);
const data = reactive({
  form: {
    sysOrgCertificateList: []
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    cityCode: -1,
    areaCode: -1,
    provinceCode: -1,
  },
  rules: {
    orgName: [{ required: true, message: "机构名称不能为空", trigger: "blur" }],
    keyWord: [{ required: true, message: "搜索关键字不能为空", trigger: "blur" }],
    areaCode: [
      { required: true, message: "公司地区不能为空", trigger: "blur" }
    ],
    personPhonenumber: [
      {
        pattern: /^\d{11}$/,

        message: "请输入正确的手机号码",
        trigger: "blur"
      }
    ],
    bankNumber: [{ pattern: /^([0-9 ])*$/, message: "请输入数字或者空格" }],
    busPhonenumber: [
      {
        pattern: /^\d{11}$/,

        message: "请输入正确的手机号码",
        trigger: "blur"
      }
    ],
    orgEmail: [
      {
        pattern: /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/,
        message: "请输入正确的邮箱",
        trigger: "blur"
      }
    ],
    taxpayerNumber: [
      { pattern: /^([0-9a-zA-Z])*$/, message: "请输入数字或者字母" }
    ],
    userName: [
      { required: true, message: "管理员账号不能为空", trigger: "blur" },
      { pattern: /^([0-9a-zA-Z])*$/, message: "请输入数字或者字母" }
    ],
    invoiceCount: [{ pattern: /^([0-9])*$/, message: "请输入数字或者字母" }],
    jclbIds: [{ required: true, message: "检测类别不能为空", trigger: "blur" }],
  },
  certificateRules: {
    certificateName: [
      { required: true, message: "证书名称不能为空", trigger: "blur" }
    ]
  }
});

const { queryParams, form, rules, certificateRules } = toRefs(data);

function handleAdd() {
  checkbox.value = true;
  disabled.value = false;
  open.value = true;
  title.value = "新增/编辑资质文件";
  certificateForm.value = { status: "0" };
  if (proxy.$refs["listRef"]) {
    proxy.$refs["listRef"].clearValidate();
  }
}

function getList() {
  loading.value = true;
  listOrg(queryParams.value).then(res => {
    orgTable.value = res.rows;
    total.value = res.total;
    loading.value = false;
  });
}

function submitForm() {
  proxy.$refs["orgRef"].validate(valid => {
    if (valid) {
      delete form.value.delFlag;
      addOrg(form.value).then(res => {
        if (form.value.orgId) {
          proxy.$modal.msgSuccess("编辑成功");
          getList();
        } else {
          form.value.orgId = res.data;
          proxy.$modal.msgSuccess("新增成功");
          heightBright.value = res.data
          resetQuery();
        }
      });
    }
  });
}

function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.orgId);
  multiple.value = selection.length;
}

function handleDelete(row) {
  const orgId = row.orgId || ids.value;
  proxy.$modal
    .confirm("是否确认删除选中的数据项？")
    .then(function () {
      return delOrg(orgId);
    })
    .then(() => {
      handleAddOrg();
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => { });
}

function reset() {
  queryParams.value = {
    orgName: null,
    cityCode: -1,
    areaCode: -1,
    provinceCode: -1,
  };
}

function resetQuery() {
  areaRef.value.resetArea();
  reset();
  handleQuery();
}

function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

function handleAddOrg() {
  zsLoading.value = false;
  highLightRow.value = false;
  heightBright.value = ""
  proxy.$refs["orgRef"].clearValidate();
  if (proxy.$refs["listRef"]) {
    proxy.$refs["listRef"].clearValidate();
  }
  form.value = {};
  viewCity.value = {}
  form.value.sysOrgCertificateList = [];
}

function cityQueryParam(val) {
  if (val.id == "left") {
    queryParams.value = Object.assign(queryParams.value, val);
  } else if (val.id == "right") {
    form.value = Object.assign(form.value, val);
  }
}

function areaCode(val) {
  form.value.areaCode = val;
}

function sava() {
  proxy.$refs["listRef"].validate(valid => {
    if (valid) {
      if (checkbox.value) {
        if (!certificateForm.value.startDate) {
          proxy.$modal.msgError('开始时间必填')
          return
        }
      } else {
        if (!certificateForm.value.startDate) {
          proxy.$modal.msgError('开始时间必填')
          return
        }
        if (!certificateForm.value.endDate) {
          proxy.$modal.msgError('结束时间必填')
          return
        }
      }
      if (!certificateForm.value.certificateId) {
        getSeqId().then(res => {
          certificateForm.value.certificateId = res.data;
          form.value.sysOrgCertificateList.push(
            JSON.parse(JSON.stringify(certificateForm.value))
          );
        });
      } else {
        form.value.sysOrgCertificateList[certificateForm.value.index] =
          certificateForm.value;
      }
      open.value = false;
    }
  });
}

function Cancel() {
  open.value = false;
}

function handleListDelete(row) {
  disabled.value = false;
  proxy.$modal
    .confirm("是否确认该条删除数据项？")
    .then(function () {
      form.value.sysOrgCertificateList.splice(row, 1);
    })
    .then(() => {
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => { });
}

function handleListEditor(row, index) {
  if (proxy.$refs["listRef"]) {
    proxy.$refs["listRef"].clearValidate();
  }
  if (row.endDate) {
    checkbox.value = false;
  } else {
    checkbox.value = true;
  }
  disabled.value = false;
  form.value.sysOrgCertificateList[index] = JSON.parse(JSON.stringify(row));
  open.value = true;
  certificateForm.value = row;
  certificateForm.value.index = index;
}

function handleListView(row) {
  proxy.$refs["listRef"].clearValidate();
  if (row.endDate) {
    checkbox.value = false;
  } else {
    checkbox.value = true;
  }
  disabled.value = true;
  open.value = true;
  certificateForm.value = row;
}

const viewCity = ref({})
function rowClick(row) {
  proxy.$refs["orgRef"].clearValidate();
  zsLoading.value = true;
  form.value = { sysOrgCertificateList: [] };
  getOrg(row.orgId).then(res => {
    form.value = res.data;
    heightBright.value = row.orgId
    viewCity.value = {
      areaCode: res.data.areaCode,
      provinceCode: res.data.provinceCode,
      cityCode: res.data.cityCode
    };
    zsLoading.value = false;
  });
}

function checkboxCheck() {
  delete certificateForm.value.endDate;
}

function endDateChange() {
  checkbox.value = false;
}

getList();

watch(() => total.value, () => {
  if (total.value) {
    heightParams.value = [{ tableName: "main", bottomHeight: 73 }, { tableName: "sub", bottomHeight: 25 }]
  } else {
    heightParams.value = [{ tableName: "main", bottomHeight: 22 }, { tableName: "sub", bottomHeight: 25 }]
  }
  getTableHeight()
})

const heightParams = ref([
  { tableName: "main", bottomHeight: 22 },
  { tableName: "sub", bottomHeight: 25 }
]);
function getTableHeight() {
  proxy.adaptiveHeight(proxy, heightParams.value);
}
onMounted(() => {
  nextTick(() => {
    getTableHeight();
    window.addEventListener("resize", getTableHeight);
  })
})
onUpdated(() => {
  nextTick(function () {
    getTableHeight();
  });
});
onBeforeUnmount(() => {
  window.removeEventListener("resize", getTableHeight);
});

const heightBright = ref("")
function tableRowClass({ row }) {
  if (row) {
    if (row.orgId == heightBright.value) {
      return "current-row";
    }
    return "";
  }
}
</script>

<style></style>